<template>
  <el-dialog v-model="visible" width="90%">
    <h2 class="title">护理项目管理</h2>

    <div class="info-bar">
      客户姓名：{{ clientName }}　|　护理级别：{{ levelName }}
    </div>

    <!-- 已购买项目 -->
    <el-table :data="tableData" border class="custom-table" :header-cell-style="headerStyle" :cell-style="cellStyle"
      v-loading="loading">
      <el-table-column prop="nursingProject.projectId" label="项目编号" width="100" />
      <el-table-column prop="nursingProject.name" label="项目名称" />
      <el-table-column prop="nursingProject.price" label="价格" />
      <el-table-column prop="clientNursingProject.quantity" label="数量" />
      <el-table-column prop="clientNursingProject.endDate" label="服务到期日期" />
      <el-table-column label="状态" width="180">
        <template #default="scope">
          <el-tag :type="scope.row.expired === 1 ? 'danger' : 'success'" style="margin-right: 8px;">
            {{ scope.row.expired === 1 ? '已到期' : '未到期' }}
          </el-tag>
          <el-tag :type="scope.row.arrears === 0 ? 'danger' : 'success'">
            {{ scope.row.arrears === 0 ? '欠费' : '数量正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button type="danger" size="small" @click="remove(scope.row)">移除</el-button>
          <el-button type="primary" size="small" @click="openRenew(scope.row)">续费</el-button>
        </template>
      </el-table-column>


    </el-table>

    <!-- 分页条 -->
    <div class="pagination-bar">
      <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size" :total="pagination.total"
        :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 确认按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleClose">确认</el-button>
    </div>

    <renew-project-dialog ref="renewDialogRef" @renew-success="fetchData" />
  </el-dialog>
</template>
<script setup>
import { ref, defineExpose } from 'vue'
import { inject } from 'vue'
const axios = inject("axios")
import { ElMessage } from 'element-plus'
import RenewProjectDialog from './RenewProjectDialog.vue'
import { ElMessageBox } from 'element-plus'

const visible = ref(false)
const clientName = ref('')
const clientId = ref(null)
const levelId = ref(null)
const levelName = ref('')
const tableData = ref([])
const renewDialogRef = ref(null)
const loading = ref(false)

const pagination = ref({ cur: 1, size: 5, total: 0 })

const headerStyle = { background: '#f9fafc', color: '#333', textAlign: 'center' }
const cellStyle = { textAlign: 'center' }

const open = async (cid, cname, lid, lname) => {
  visible.value = true
  clientId.value = cid
  clientName.value = cname
  levelId.value = lid
  levelName.value = lname
  pagination.value.cur = 1
  await fetchData()
}

const handleSizeChange = (s) => {
  pagination.value.size = s
  pagination.value.cur = 1
  fetchData()
}
const handleCurrentChange = (p) => {
  pagination.value.cur = p
  fetchData()
}

const handleClose = () => {
  visible.value = false
}

const remove = async (row) => {
  try {
    await ElMessageBox.confirm(
      `
      <div style="font-size: 16px; line-height: 1.8; padding: 5px 0;">
        是否确认<strong style="color: #f56c6c;">移除该护理项目</strong>？
        <br />
        <span style="color: #909399;">注意：移除后将 <strong style="color: red;">无法恢复</strong>。</span>
      </div>
      `,
      '操作确认',
      {
        confirmButtonText: '确定移除',
        cancelButtonText: '取消操作',
        dangerouslyUseHTMLString: true,
        type: 'warning',
        center: true,
        showClose: false,
        customClass: 'confirm-dialog-custom'
      }
    )

    // 确认后执行移除
    const res = await axios.post(
      '/clientNursingProject/deleteClientNursingProjectById',
      null,
      {
        params: {
          clientId: clientId.value,
          projectId: row.nursingProject.projectId,
          levelId: levelId.value
        }
      }
    )

    if (res.data.status === 200) {
      ElMessage.success('移除成功')
      fetchData()
    } else {
      throw new Error(res.data.msg)
    }

  } catch (err) {
    // 用户取消或异常
    if (err !== 'cancel' && err !== 'close') {
      ElMessage.error('移除失败：' + err.message)
    }
    // 用户取消操作则安静处理
  }
}


const fetchData = async () => {
  loading.value = true
  try {
    const res = await axios.get('/clientNursingProject/pageClientAndProjectByName', {
      params: {
        cur: pagination.value.cur,
        number: pagination.value.size,
        name: clientName.value
      }
    })
    if (res.data.status === 200) {
      const rawData = res.data.data || []
      // 并发请求每行的状态信息
      const withStatus = await Promise.all(
        rawData.map(async (row) => {
          const projectId = row.nursingProject.projectId
          const [expireRes, costRes] = await Promise.all([
            axios.post('/clientNursingProject/judgeNursingProjectExpiration', null, {
              params: { clientId: clientId.value, levelId: levelId.value, projectId }
            }),
            axios.post('/clientNursingProject/judgeNursingProjectCost', null, {
              params: { clientId: clientId.value, levelId: levelId.value, projectId }
            })
          ])
          return {
            ...row,
            expired: expireRes.data?.data ?? 0,
            arrears: costRes.data?.data ?? 0
          }
        })
      )
      tableData.value = withStatus
      pagination.value.total = res.data.total
    }
  } catch (err) {
    ElMessage.error('获取数据失败：' + err.message)
  } finally {
    loading.value = false
  }
}


const openRenew = (row) => {
  renewDialogRef.value.open(row)
}

defineExpose({ open })
</script>
<style scoped>
.title {
  font-size: 27.2px;
  font-weight: bold;
  margin: 0 0 20px 0;
  color: #333;
}

.info-bar {
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.custom-table {
  background: #f5f7fa;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 2%;
  margin-bottom: 2%;
}

.action-bar {
  text-align: center;
  margin-top: 20px;
}
</style>
